#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/7/20 11:33
# @Author  : Samge
import json
import sys

from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QWidget, QCheckBox

from itkz.resources.utils import config_util
from itkz.resources.view_field_list import Ui_Form


# 字段名映射
FIELD_MAP = {
        '状态': 'field_status',
        'dataId': 'field_dataId',
        '标题': 'field_title',
        '关键词': 'field_keyword',
        '排序字段': 'field_order_by',
        '查询字段': 'field_query_fields',
        '其他参数': 'field_other_params',
        '分组字段': 'field_group_by',
        '省': 'field_province',
        '市': 'field_city',
        '区': 'field_area',
    }


class FieldListWidget(QWidget, Ui_Form):

    # 当前按钮文字
    bt_text = '全选'
    bt_text_un = '反选'

    # 窗口关闭的信号
    close_signal = QtCore.pyqtSignal(str)

    # 当前点击(要绑定)的标签名
    curr_bind_label_text = ''

    settingsName = None

    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setupUi(self)
        self.setupFieldsKey([])

    def setupFieldsKey(self, data_list):
        """
        初始化字段列表
        :param data_list:
        :return:
        """
        self.remove_all()
        self.bt_selected.setText(self.bt_text)
        for data in data_list or []:
            qc = QCheckBox(self)
            qc.setText(data)
            self.list_view.addWidget(qc)
        self.parse_all()

    def remove_all(self):
        """
        清除所有子view
        :return:
        """
        for i in range(self.list_view.count()):
            self.list_view.removeItem(self.list_view.itemAt(i))

    def get_data(self):
        """
        获取当前选中的字段列表 字典
        :return:
        """
        return {
            'fields': self.get_fields(),
        }

    def get_fields(self):
        """
        获取当前选择的字段
        :return:
        """
        fields = []
        self.list_view.children()
        for i in range(self.list_view.count()):
            view = self.list_view.itemAt(i).widget()
            if view.isChecked():
                fields.append(view.text())
        # print(fields)
        return fields

    def parse_select(self, is_checked_all):
        """
        处理全选/反选事件的ui刷新
        :param is_checked_all: 是否全选
        :return:
        """
        txt = self.bt_text_un if is_checked_all else self.bt_text
        self.bt_selected.setText(txt)
        for i in range(self.list_view.count()):
            self.list_view.itemAt(i).widget().setChecked(is_checked_all)

    def parse_all(self):
        """
        处理 全选/反选 的按钮点击事件
        :return:
        """
        is_checked_all = True if self.bt_text == self.bt_selected.text() else False
        self.parse_select(is_checked_all)

    def closeEvent(self, event):
        """
        窗口关闭的事件处理,这里将该事件发送到外部处理
        :param event:
        :return:
        """
        print('窗口关闭')
        result = {
            'name': self.curr_bind_label_text,
            'field_key': FIELD_MAP.get(self.curr_bind_label_text),
            'fields': self.get_fields()
        }
        self.set_curr_bind_label_text('')
        self.close_signal.emit(json.dumps(result, ensure_ascii=False))

    # 可在外部与槽函数连接
    def connect_clicked_slot(self, func):
        self.close_signal.connect(func)

    def set_curr_bind_label_text(self, txt):
        """
        设置当前要绑定的标签名
        :param txt:
        :return:
        """
        self.curr_bind_label_text = txt

        field_keys = config_util.value(f"{self.settingsName}/{FIELD_MAP.get(txt)}", [])
        if not field_keys:
            return
        if type(field_keys) is str:
            field_keys = [field_keys]
        for i in range(self.list_view.count()):
            item_text = self.list_view.itemAt(i).widget().text()
            for key in field_keys:
                if key == item_text:
                    self.list_view.itemAt(i).widget().setChecked(True)

    def setupQSettingsName(self, name):
        """
        初始化缓存配置的根名字  可以理解为 [配置域]
        :param name:
        :return:
        """
        self.settingsName = name


def main():
    app = QtWidgets.QApplication(sys.argv)
    gui = FieldListWidget()
    gui.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
